package finbudgettable.client.ui.grid.cell.permission;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;
import com.gwtplatform.mvp.client.Presenter;

import finbudget.client.permissions.PermissionPresenter;
import finbudget.client.ui.table.Record;
import finbudget.client.ui.table.fields.PermissionField;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.column.GridColumn;

public class PermissionColumn extends GridColumn<String> {

	interface PermissionMessages extends Messages {
		@DefaultMessage("Права")
		String permissions();
	}

	private final static PermissionMessages MESSAGES = GWT.create(PermissionMessages.class);

	public static class Builder extends GridColumn.Builder<PermissionCell, String> {

		private final PermissionPresenter permissionsPresenter;
		private final CellGrid grid;

		protected Builder(CellGrid grid, PermissionField field, PermissionPresenter permissionsPresenter, boolean hasTotals) {
			super(grid, field.captionGrid, hasTotals);
			this.permissionsPresenter = permissionsPresenter;
			this.grid = grid;
			setCaption(field.captionGrid);
		}

		@Override
		protected PermissionCell createCell() {
			return new PermissionCell();
		}

		@Override
		protected GridColumn<String> createColumn(Cell<String> cell) {
			return new PermissionColumn(this);
		}

	}

	protected PermissionColumn(final Builder builder) {
		super(builder);
		setFieldUpdaterDirectly(new FieldUpdater<Record, String>() {

			@Override
			public void update(int index, Record record, String value) {
				if (!record.toDelete) {
					Presenter<?, ?> myPresenter = builder.grid.getMyPresenter();
					if (myPresenter != null) {
						builder.permissionsPresenter.setKey(record.key);
						myPresenter.addToPopupSlot(builder.permissionsPresenter);
					}
				}
			}

		});
	}

	@Override
	protected boolean isValueChanged(Record record, String value) {
		return false;
	}

	@Override
	public String getValue(Record record) {
		return record.toDelete ? null : MESSAGES.permissions();
	}

	@Override
	public String toString() {
		return MESSAGES.permissions();
	}

	public static Builder builder(CellGrid grid, PermissionField field, PermissionPresenter permissionsPresenter, boolean hasTotals) {
		return new Builder(grid, field, permissionsPresenter, hasTotals);
	}

}
